import { reactive, computed, toRefs } from 'vue';
import { PaginationQuery, Pagination } from '@/types/table';
import { TableState, CheckAble } from '@/types/table';

import { getskuGoodsSku } from '@/api/goods';

const tableQuery: PaginationQuery = reactive({
    page: 0,
    size: 10,
    sort: 'id,desc',
    blurry: '',
});

// 编辑用户
const state: TableState & CheckAble = reactive({
    dataSource: [],
    selectedRow: {},
    selectedRowKeys: [],
    visible: false,
    loading: false,
    showType: 'add',
    pagination: {
        total: 0,
        current: computed(() => tableQuery.page + 1),
    },
});

// 页码改变
const handleTableChange = (pagination: Pagination) => {
    const { current } = pagination;
    tableQuery.page = current - 1;
    getskuGoodsSkuList(tableQuery);
};
const listFormSubmit = () => {
    getskuGoodsSkuList(tableQuery);
    state.visible = false;
};

// 获取表格数据
const getskuGoodsSkuList = async (params: PaginationQuery) => {
    const { content, totalElements } = await getskuGoodsSku(params);
    content.forEach((i) => {
        i.skuStr = JSON.parse(i.skuStr);
        i.skuStr = objToArr(i.skuStr);
    });
    state.loading = false;
    state.dataSource = content;
    state.pagination.total = totalElements;
};

const objToArr = (obj: any) => {
    const arr = [];
    for (const i in obj) {
        const o: any = {};
        o[i] = obj[i];
        o.code = i;
        arr.push(o);
    }
    return arr;
};

// 显示新增用户弹窗
const handleAdd = () => {
    state.selectedRow = {};
    state.selectedRowKeys = [];
    state.visible = true;
    state.showType = 'add';
};
// 显示新增用户弹窗
const handleEdit = (row: any, type: string) => {
    console.log(type);
    console.log(row);
    state.selectedRow = row;
    state.visible = true;
    state.showType = type;
};

export default {
    tableQuery,
    handleTableChange,
    getskuGoodsSkuList,
    handleAdd,
    objToArr,
    handleEdit,
    ...toRefs(state),
    listFormSubmit,
};
